package ar.com.globallogic.promomr.services;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import ar.com.globallogic.promomr.domain.Folder;
import ar.com.globallogic.promomr.exceptions.FolderNotFoundException;
import ar.com.globallogic.promomr.persistance.FolderRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Service
public class FolderServiceImpl implements FolderService{

	private static final Logger logger = LoggerFactory.getLogger(FolderServiceImpl.class);

	private FolderRepository folderRepository;
	
	@Autowired
	public FolderServiceImpl(FolderRepository folderRepository){
		this.folderRepository = folderRepository;
	}
	
	public Folder findOne(String id) {
		logger.info(String.format("Finding folder with id %s.", id));
		Folder folder = folderRepository.findOne(id);
		if(folder == null){
			logger.error(String.format("Folder with id %s was not found.", id));
			throw new FolderNotFoundException(id);
		}
		logger.info(String.format("Folder with id %s was found.", id));
		return folder;
	}

	public Folder save(Folder folder) {
		Folder parent = this.findOne(folder.getParentId());
		parent.testNameForChild(folder);
		folderRepository.save(folder);
		parent.addChild(folder);
		folderRepository.save(parent);
		logger.info(String.format("Folder with name %s was saved.", folder.getName()));
		return folder;
	}

}
